﻿using Microsoft.Data.Sqlite;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace Znice.Test
{
    public partial class FrmEditor : Form
    {
        private readonly RichDemo? editModel;
        public FrmEditor(RichDemo? editModel = null)
        {
            InitializeComponent();
            this.editModel = editModel;
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            if (txtEditor.RichText?.Length > 0)
            {
                RichDemo model = new()
                {
                    Title = txtTitle.Text,
                    Content = txtEditor.RichText
                };
                int rows = Save(model);
                if (rows > 0)
                {
                    DialogResult = DialogResult.OK;
                }
            }
        }

        private int Save(RichDemo model)
        {
            int rows = 0;
            try
            {
                // 定义 SQLite 连接字符串
                string connectionString = "Data Source=demo.db;";

                // 创建一个新的 SQLite 连接
                using (SqliteConnection connection = new(connectionString))
                {
                    // 打开连接
                    connection.Open();

                    // 定义 SQL 查询语句
                    string sql = "INSERT INTO RichDemo (Title, Content) VALUES (@Title, @Content);";
                    if (editModel != null)
                    {
                        sql = "UPDATE RichDemo SET Title = @Title, Content = @Content WHERE Id = @Id";
                    }

                    // 创建一个新的 SQLiteCommand 对象
                    using (SqliteCommand command = new(sql, connection))
                    {
                        // 添加参数
                        command.Parameters.AddWithValue("@Title", model.Title);
                        command.Parameters.AddWithValue("@Content", model.Content);
                        if (editModel != null)
                        {
                            command.Parameters.AddWithValue("@Id", editModel.Id);
                        }

                        // 执行 SQL 查询语句
                        rows = command.ExecuteNonQuery();
                    }
                }
            }
            catch(Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
            return rows;
        }

        private void FrmEditor_Load(object sender, EventArgs e)
        {
            if (editModel != null)
            {
                txtTitle.Text = editModel.Title;
                txtEditor.RichText = editModel.Content;
            }
        }
    }
}
